const parseTime = (time, format = 'YYYY-MM-DD h:m:s') => {
    if (!format) return time
    else {
        if ( !isNaN( Date.parse(time) ) &&  Date.parse(time) > 0) {
            const formatObj = {
                YYYY: time.getFullYear(),
                MM: time.getMonth() + 1,
                DD: time.getDate(),
                hh: time.getHours(),
                mm: time.getMinutes(),
                ss: time.getSeconds(),
                a: time.getDay()
            }
            const time_str = format.replace(/(YYYY|MM|DD|h|m|s|a)/g, (result, key) => {
                let value = formatObj[key]
                if (key === 'a') return ['日', '一', '二', '三', '四', '五', '六'][value]
                return String(value).padStart(2, '0')
            })
            return time_str
            
        } else {
            throw new Error('需要日期格式')
        }
    }
}

const treatTime = (time) => {
    if (time == '' || time == null) return false
    // 判断是否是日期格式  new Date
    if ( !isNaN( Date.parse(time) ) &&  Date.parse(time) > 0) {
        return time
    // 时间戳格式 32131231231231
    } else if ( /^\d+$/.test(time) ) {
        return new Date(time)
    // 处理过的日期格式 2023-05-23
    } else if ( /\d{4}-\d{1,2}-\d{1,2}/.test(time) ) {
        return new Date(time)
    } else {
        return false
    }
}

export const getDateBefore = (time, day = 3, format) => {
    let newtime = treatTime(time)
    if (!newtime) return
    return parseTime(new Date(newtime.setDate(newtime.getDate() - day)), format)
}